package com.chase.passwordmaster.detail.edit

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import com.chase.passwordmaster.R
import com.chase.passwordmaster.data.AccountViewModel
import com.chase.passwordmaster.entity.DecryptedAccount
import com.chase.passwordmaster.utils.showAlert
import com.chase.passwordmaster.utils.showToast
import com.chase.passwordmaster.utils.useDarkStatusBar
import com.chase.passwordmaster.utils.useImmersingNavigator
import com.mylhyl.circledialog.CircleDialog

class EditActivity : AppCompatActivity() {

    companion object {
        fun actionStart(context: Context, accountIndex: Int) {
            val intent = Intent(context, EditActivity::class.java)
            intent.putExtra("accountIndex", accountIndex)
            context.startActivity(intent)
        }
    }

    private lateinit var accountViewModel: AccountViewModel

    private var accountIndex = -1
    private lateinit var account: DecryptedAccount

    private lateinit var cpBack: View
    private lateinit var etWebsite: EditText
    private lateinit var etUsername: EditText
    private lateinit var etPassword: EditText
    private lateinit var etName: EditText
    private lateinit var etTel: EditText
    private lateinit var etEMail: EditText
    private lateinit var etQQ: EditText
    private lateinit var etWeChat: EditText
    private lateinit var etMemo: EditText

    private lateinit var save: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit)

        accountViewModel = ViewModelProviders.of(this).get(AccountViewModel::class.java)

        cpBack = findViewById(R.id.back_edit)
        etWebsite = findViewById(R.id.et_website_edit)
        etUsername = findViewById(R.id.et_username_edit)
        etPassword = findViewById(R.id.et_password_edit)
        etName = findViewById(R.id.et_name_edit)
        etTel = findViewById(R.id.et_tel_edit)
        etQQ = findViewById(R.id.et_qq_edit)
        etEMail = findViewById(R.id.et_email_edit)
        etWeChat = findViewById(R.id.et_wechat_edit)
        etMemo = findViewById(R.id.et_memo_edit)

        save = findViewById(R.id.save_edit)

        useDarkStatusBar()
        useImmersingNavigator()

        // Get information from intent
        accountIndex = intent.getIntExtra("accountIndex", -1)
        Log.d("GSC:AddActivity", "accountIndex:$accountIndex")

        account = if (accountIndex != -1) {
            accountViewModel.getAccount(accountIndex) ?: DecryptedAccount("error", "error", "error")
        } else DecryptedAccount("error", "error", "error")

        account.run {
            etWebsite.setText(website)
            etUsername.setText(username)
            etPassword.setText(password)
            etName.setText(name)
            etTel.setText(tel)
            etQQ.setText(qq)
            etEMail.setText(email)
            etWeChat.setText(weChat)
            etMemo.setText(memo)
        }

        initCPBack(cpBack = cpBack)
        initSave()
    }

    private fun isUnchanged(): Boolean {
        return account.run {
            etWebsite.text.toString() == website &&
                    etUsername.text.toString() == username &&
                    etPassword.text.toString() == password &&
                    (etTel.text.toString() == tel || (etTel.text.isBlank() && tel.isNullOrBlank())) &&
                    (etQQ.text.toString() == qq || (etQQ.text.isBlank() && qq.isNullOrBlank())) &&
                    (etWeChat.text.toString() == weChat || (etWeChat.text.isBlank() && weChat.isNullOrBlank())) &&
                    (etEMail.text.toString() == email || (etEMail.text.isBlank() && email.isNullOrBlank())) &&
                    (etName.text.toString() == name || (etName.text.isBlank() && name.isNullOrBlank())) &&
                    (etMemo.text.toString() == memo || (etMemo.text.isBlank() && memo.isNullOrBlank()))
        }
    }

    override fun onBackPressed() {
        if (isUnchanged()) {
            super.onBackPressed()
        } else {
            CircleDialog.Builder()
                .setRadius(20)
                .setWidth(0.8f)
                .setTitle("退出修改")
                .setText("\n返回将不会保存您的修改\n")
                .setPositive("不保存") {
                    super.onBackPressed()
                }
                .setNegative("取消", null)
                .show(supportFragmentManager)
        }
    }

    private fun initCPBack(cpBack: View) {
        cpBack.setOnClickListener { onBackPressed() }
    }

    private fun initSave() {
        fun isRequiredValid() =
            etWebsite.text.isNotBlank() && etUsername.text.isNotBlank() && etPassword.text.isNotBlank()

        save.setOnClickListener {
            if (isRequiredValid()) {
                var hasDefaultField = false

                account.apply {
                    website = etWebsite.text.toString()
                    username = etUsername.text.toString()
                    password = etPassword.text.toString()
                    name = when {
                        etName.text?.isNotBlank() == true -> etName.text.toString()
                        name != null -> run {
                            setToDefault("name")
                            hasDefaultField = true
                            null
                        }
                        else -> name
                    }

                    tel = when {
                        etTel.text?.isNotBlank() == true -> etTel.text.toString()
                        tel != null -> run {
                            setToDefault("tel")
                            hasDefaultField = true
                            null
                        }
                        else -> tel
                    }

                    qq = when {
                        etQQ.text?.isNotBlank() == true -> etQQ.text.toString()
                        qq != null -> run {
                            setToDefault("qq")
                            hasDefaultField = true
                            null
                        }
                        else -> qq
                    }

                    email = when {
                        etEMail.text?.isNotBlank() == true -> etEMail.text.toString()
                        email != null -> run {
                            setToDefault("email")
                            hasDefaultField = true
                            null
                        }
                        else -> email
                    }

                    weChat = when {
                        etWeChat.text?.isNotBlank() == true -> etWeChat.text.toString()
                        weChat != null -> run {
                            setToDefault("weChat")
                            hasDefaultField = true
                            null
                        }
                        else -> weChat
                    }

                    memo = when {
                        etMemo.text?.isNotBlank() == true -> etMemo.text.toString()
                        memo != null -> run {
                            setToDefault("memo")
                            hasDefaultField = true
                            null
                        }
                        else -> memo
                    }
                }

                if (hasDefaultField) {
                    account.id?.let { account.updateAll("id = ?", "$it") }
                    Logger.v("db", "call updateAll(), account.id=${account.id}")
                } else {
                    if (!account.save()) {
                        Logger.e("db", "Failed to call save() to update, account.id=${account.id}")
                    } else {
                        Logger.v("db", "Success to call save() to update, account.id=${account.id}")
                    }
                }

                accountViewModel.getAccountLiveData().value?.run {
                    accountViewModel.getAccountLiveData().value = this
                }
                this.finish()
            } else {
                showToast("必填项不能为空", Toast.LENGTH_LONG)
            }
        }
    }
}